package com.example.javaee.Util;

import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {

    /**
     * token过期时间
     */
    public static final long JWT_TOKEN_VALIDITY = 5*60*60*1000;

    /**
     * token的密钥
     */
    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private UserMapper userMapper;

    public String generateToken(String userName) {
        User user = userMapper.selectByName(userName);

        Map<String, Object> claims = new HashMap<>();
        return Jwts.builder()
                .claim("userId",user.getId())
                .claim("userName",user.getUsername())
                .claim("avatar",user.getAvatar())
                .claim("type",user.getType())
                .setSubject(userName)       //认证的主体
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     * 解析
     * @param token
     * @return
     */
    public Claims getClaimFromToken(String token) {
        return (Claims)Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }
}
